package com.ramnight.unify.boot.web;

import com.alibaba.fastjson.JSON;
import com.ramnight.unify.kit.exception.ExceptionUtil;
import com.ramnight.unify.kit.exception.UnifyException;

import lombok.Data;

@Data
public class UnifyResp {
	private static final int SUCCESS_CODE = 1;

	private int code;
	private String msg;
	private Object data;

	private UnifyResp() {
	}

	public static UnifyResp success() {
		return success(null);
	}

	public static UnifyResp success(Object data) {
		UnifyResp resp = new UnifyResp();
		resp.code = SUCCESS_CODE;
		resp.data = data;
		return resp;
	}

	public static UnifyResp error(Exception e) {
		UnifyResp resp = new UnifyResp();
		if (e instanceof UnifyException) {
			resp.code = ((UnifyException) e).getCode();
			resp.msg = ((UnifyException) e).getMsg();
		} else {
			resp.msg = ExceptionUtil.getDescription(e);
		}
		return resp;
	}

	public static UnifyResp error(String msg) {
		return error(0, msg);
	}

	public static UnifyResp error(int code) {
		return error(code, null);
	}

	public static UnifyResp error(int code, String msg) {
		UnifyResp resp = new UnifyResp();
		resp.code = code;
		resp.msg = msg;
		return resp;
	}

	@Override
	public String toString() {
		return JSON.toJSONString(this);
	}
}
